import { createRouter, createWebHashHistory } from "vue-router"
import { useLoginStore } from "../store/loginStore"
import { message } from "ant-design-vue"

const routes = [
    {
        path: "/login",
        name: "login",
        component: () => import("../views/Login.vue")
    },
    {
        path: "/",
        name: "home",
        component: () => import("../views/Home.vue")
    },
    {
        path: "/admin",
        name: "admin",
        component: () => import("../views/Admin.vue")
    },
    {
        path: "/:catchAll(.*)",
        name: "404",
        component: () => import("../views/404.vue")
    },
]

const router = createRouter({
    history: createWebHashHistory(),
    routes
})

router.beforeEach((to,_form,next) => {
    if (to.name === "404") {
        next()
        return
    }
    const loginStore = useLoginStore()
    if (to.name === "login") {
        if (loginStore.isAuthenticated()) {
            message.warn("你已经登录过了")
            next("/")
        } else {
            next()
        }
        return
    }

    if (to.name === "admin") {
        if (loginStore.$state.roles.includes('admin')) {
            next()
        } else {
            message.warn("你没有权限这样做")
            next("/")
        }
        return
    }

    next()
})

export default router